<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #box {
            width: 300px;
            height: 300px;
            position: absolute;
            top: 0;
            left: 0;
            background-color: #0f0;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        var box = document.getElementById("box");
        box.onmousedown = function (e) {
            var e = window.event || e;
            //clientX  鼠标移动的坐标 offsetLeft 偏移量
            var x = e.clientX - box.offsetLeft;
            var y = e.clientY - box.offsetTop;
            document.onmousemove = function (e) {
                var e = window.event || e;
                box.style.left = e.clientX - x + "px";
                box.style.top = e.clientY - y + "px";
            }
        }
        box.onmouseup=function(){
            document.onmousemove=null;
        }
    </script>
</body>

</html>